package com.ssms.service;

import com.ssms.commons.Result;
import com.ssms.commons.TablePage;
import com.ssms.dao.ClazzMapper;
import com.ssms.dao.SubjectMapper;
import com.ssms.dao.SysUserMapper;
import com.ssms.model.Clazz;
import com.ssms.model.SysUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
public class ClazzService {

    @Resource
    private ClazzMapper clazzMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    public Result save(Clazz clazz) {
        if (check(clazz)) {
            return Result.failed("班级编号已存在", 500);
        }

        int count = clazzMapper.insertSelective(clazz);
        return count > 0?Result.success():Result.failed("添加失败", 500);
    }


    public TablePage search(TablePage tablePage, Integer subjectId) {
        int size = tablePage.getLimit();
        int start = (tablePage.getPage() - 1) * size;
        // 获取分页数据
        List<Clazz> roles = clazzMapper.selectPage(start, size, subjectId);
        // 获取符合条件的总数
        int count = clazzMapper.selectPageCount(subjectId);
        tablePage.setCount(count);
        tablePage.setData(roles);
        return tablePage;
    }

    public Result update(Clazz clazz) {
        if (check(clazz)) {
            return Result.failed("班级编号已存在", 500);
        }

        int count = clazzMapper.updateByPrimaryKeySelective(clazz);
        return count > 0?Result.success():Result.failed("更新失败", 500);
    }

    // 检查班级编号是否存在
    private boolean check(Clazz clazz){
        List<Clazz> objs= clazzMapper.selectByClazzNo(clazz.getClazzNo());

        Iterator<Clazz> iterator = objs.iterator();
        while (iterator.hasNext()){
            Clazz clz = iterator.next();
            if(clz.getId() == clazz.getId()){
                iterator.remove();
            }
        }

        for (Clazz obj : objs) {
            if(obj.getClazzNo() == clazz.getClazzNo() && obj.getSubjectId() == clazz.getSubjectId()){
                return true;
            }
        }

        return false;
    }

    public Result delete(Integer id) {
        List<SysUser> sysUsers = sysUserMapper.selectAllByClazzId(id);
        if(sysUsers != null && sysUsers.size() > 0){
            return Result.failed("班级存在学生，不能删除", 500);
        }
        int count = clazzMapper.deleteByPrimaryKey(id);
        return count > 0?Result.success():Result.failed("删除失败", 500);
    }

    public Result all(Integer subjectId) {
        return Result.success(clazzMapper.selectAll(subjectId));
    }

}
